// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "fortuneserver.h"
#include "fortunethread.h"

#include <QRandomGenerator>

#include <stdlib.h>

//! [0]
FortuneServer::FortuneServer(QObject *parent)
    : QTcpServer(parent)
{
    fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
             << tr("You've got to think about tomorrow.")
             << tr("You will be surprised by a loud noise.")
             << tr("You will feel hungry again in another hour.")
             << tr("You might have mail.")
             << tr("You cannot kill time without injuring eternity.")
             << tr("Computers are not intelligent. They only think they are.");
    /*在发射者中建立关联：编译提示：
    qt.core.qobject.connect: QObject::connect: Cannot connect FortuneServer::error(QString) to (nullptr)::show_err(QString)
    是因为在dialog.h中定义server时，按默认值，即parent=nullptr。
    但实测ok。
    虽然可以使用.setParent(this)设置，但构造函数时，parent是nullptr。
    */
    connect(this, SIGNAL(error(QString)), parent, SLOT(show_err(QString)));
}

void FortuneServer::set_bin_file(QString path, QString name)
{
    bin_file_name_server_path= path;
    bin_file_name_server= name;
    qDebug()<<QString("bin_file_name_server")<< bin_file_name_server_path<< bin_file_name_server;
}

//! [0]

//! [1]
void FortuneServer::incomingConnection(qintptr socketDescriptor)
{
    //QString fortune = fortunes.at(QRandomGenerator::global()->bounded(fortunes.size()));
    //QString fortune= this->parent()->get_bin_file_name(); //访问不了这个函数。
    FortuneThread *thread = new FortuneThread(socketDescriptor, bin_file_name_server_path, bin_file_name_server, this);     //每建立一次连接，传入一个新的字符串。谁来释放呢？
    connect(thread, &FortuneThread::finished, thread, &FortuneThread::deleteLater); //不能自己处理吗？不能，因为处理的是实例，不是类。

    connect(thread, &FortuneThread::error_str, this, &FortuneServer::error_to_gui);
    /*finished信号，就可以删除线程自己吗（对象/实例）。
    */
    thread->start();
    qDebug()<< "FortuneServer"<< QThread::currentThreadId();
}


void FortuneServer::error_to_gui(QString err)
{
    qDebug()<<"info from thread:"<<(quint64)sender()<< err;

    emit error(err);    //与error()关联的slot是
}

//! [1]
